<template>
  <van-nav-bar
    title="登录"
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
    placeholder
    fixed
  />
  <van-form>
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ pattern: /\w{3,}/, message: '三位以上 的数字字母下划线' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ pattern: /.{6,}/, message: '三位以上 的任意字符' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit" @click="loginFn()">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { getCartList } from '@/stores/huibiao'
let router = useRouter()
let username = ref('')
let password = ref('')
let loginApi = ref('http://localhost:3001/api/user/login')

async function loginFn() {
  let res = await axios.post(loginApi.value, {
    loginname: username.value,
    password: password.value,
  })
  let { code, message, data } = res.data
  console.log(res.data)
  if (code == 200) {
    getCartList()
    alert(message)
    let token = localStorage.setItem('token', data.token)
    let userid = localStorage.setItem('userid', data.userid)
    router.push('/')
  } else {
    alert(message)
  }
}
</script>

<style scoped>
.login {
  width: 90%;
  margin: 0 auto;
}
</style>
